package com.gobang.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gobang.domain.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * JWT认证失败处理器
 * 当用户未认证或Token无效时，返回统一的JSON响应
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        log.warn("认证失败: URI={}, 错误={}", request.getRequestURI(), authException.getMessage());

        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 构造统一响应格式
        Result<Void> result = Result.fail(401, "未认证或Token无效，请先登录");

        // 写入响应
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}

